package com.ril.google;

import java.io.IOException;
import java.util.HashMap;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.util.ServiceException;
import org.apache.commons.collections15.CollectionUtils;
import org.apache.commons.collections15.Predicate;
import org.apache.commons.lang.StringUtils;

public class DocumentsHelper {
    private DocumentList _documentList;

    public DocumentsHelper(DocumentList documentList) {
        _documentList = documentList;
    }

    public void initStorage(String folderPrefix) throws IOException, DocumentListException, ServiceException {
        DocumentListEntry rootFolder = createFolderTreeIfNotExists(folderPrefix);
        DocumentListEntry mainSpreadSheet = createMainSpreadsheetIfNotExists(rootFolder);
    }

    DocumentListEntry createMainSpreadsheetIfNotExists(DocumentListEntry rootFolder) throws IOException, DocumentListException, ServiceException {
        DocumentListFeed feed = _documentList.getFolderDocsListFeed(rootFolder.getResourceId());
        String mainSpreadsheetName = buildMainSpreadsheetName();
        DocumentListEntry mainSpreadsheet = findEntryByTitle(feed, mainSpreadsheetName);
        if (mainSpreadsheet ==null){
           mainSpreadsheet= _documentList.createNew(mainSpreadsheetName,"spreadsheet");
           initMainSpreadsheet(mainSpreadsheet);
        }
        return mainSpreadsheet;

    }

    void initMainSpreadsheet(DocumentListEntry mainSpreadsheet) {
       
    }

    private String buildMainSpreadsheetName() {
        return "main-financial.xls";
    }

    DocumentListEntry createFolderTreeIfNotExists(String folderPrefix) throws IOException, DocumentListException, ServiceException {

        final String folderName = buildMainFolderName(folderPrefix);

        HashMap<String, String> searchParameters = new HashMap<String, String>();
        searchParameters.put("title", folderName);
        searchParameters.put("title-exact", "true");

        DocumentListFeed feed = _documentList.search(searchParameters, "folders");
        DocumentListEntry rootFolder;
        if (feed.getEntries().isEmpty()) {
            rootFolder = _documentList.createNew(folderName, "folder");
        } else {
            rootFolder = feed.getEntries().get(0);
        }

        return rootFolder;
    }

    private DocumentListEntry findEntryByTitle(DocumentListFeed feed, final String entryTitle) {
        return CollectionUtils.find(feed.getEntries(), new Predicate<DocumentListEntry>() {
            public boolean evaluate(DocumentListEntry documentListEntry) {
                return StringUtils.equalsIgnoreCase(entryTitle, documentListEntry.getTitle().toString());
            }
        });
    }

    String buildMainFolderName(String folderPrefix) {
        return folderPrefix + "financial";
    }
}
